package com.example.emailcraft.interceptor;

import com.example.emailcraft.annotation.RequiredPermission;
import com.example.emailcraft.entity.dto.CurrentUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 1. 检查是否为控制器方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 2. 获取权限注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);

        // 3. 无需权限验证
        if (annotation == null) {
            return true;
        }

        // 4. 获取当前用户权限
        CurrentUser user = CurrentUserHolder.get();
        if (user == null) {
            sendError(response, 401, "用户未登录");
            return false;
        }

        // 5. 验证权限
        String requiredPermission = annotation.value();
        if (!user.getRoles().contains(requiredPermission)) {
            sendError(response, 403, "权限不足");
            return false;
        }

        return true;
    }

    private void sendError(HttpServletResponse response, int code, String msg) throws IOException {
        response.setStatus(code);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\":" + code + ",\"message\":\"" + msg + "\"}");
    }
}